package cn.edu.hqu.example.bj.experiment_6;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;




public class MainActivity extends AppCompatActivity {


    @BindView(R.id.b_1)
    public Button maymenue;

    public static final String DEF_CHATSET="UTF-8";
    public static final int DEF_CONN_TIMEOUT=30000;
    public static final int DEF_READ_TIMEOUT=30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    //配置key
    public static final String APPKEy="21622224690df6e201e8fa8641f0395b";

    //1.菜谱大全
    public static void getRequest1()
    {
        String result =null;
        String url="http://apis.juhe.cn/cook/query.php";//请求接口
        Map params = new HashMap(); //请求参数

        params.put("menu","豆腐");//需要查询的菜谱名（查询的菜名不能是空的）

        params.put("key",APPKEy);//应用接口
        params.put("dtype","");//返回类型json
        params.put("pn","");//数据返回其实下标，默认0
        params.put("rn","");//数据返回条数，默认10
        params.put("albums","");//albums字段类型，1字符串，默认数组

        //在这里建立一个网络的新线程比较好 https://blog.csdn.net/qq_15267341/article/details/52474293
        try{
            result =net(url,params,"GET");

            //菜谱返回的时候json内有list https://blog.csdn.net/jeffleo/article/details/73612224
            //用fastjson而不是用org原本的json
            JSONObject object= JSON.parseObject(result);

            if(object.getIntValue("error_code")==0)
            {
                System.out.println(object.get("result"));
            }else {
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //2.分类标签列表
    public static void getRequest2()
    {
        String result =null;
        String url="http://apis.juhe.cn/cook/query.php";
        Map params=new HashMap();
        params.put("parentid","");//分类id默认为全部
        params.put("key",APPKEy);
        params.put("dtype","");//json格式返回


        try{
            result =net(url,params,"GET");
            JSONObject object=JSON.parseObject(result);
            if(object.getIntValue("error_code")==0)
            {
                System.out.println(object.get("result"));
            }else {
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //3.按标签检索菜谱
    public static void getRequest3()
    {
        String result =null;
        String url="http://apis.juhe.cn/cook/query.php";
        Map params=new HashMap();
        params.put("cid","");//标签id
        params.put("key",APPKEy);
        params.put("dtype","");//json格式返回
        params.put("pn","");//数据返回其实下标，默认0
        params.put("rn","");//数据返回条数，默认10\
        params.put("format","");

        try{
            result =net(url,params,"GET");
            JSONObject object=JSON.parseObject(result);
            if(object.getIntValue("error_code")==0)
            {
                System.out.println(object.get("result"));
            }else {
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //4.按id查看详情
    public static void getRequest4()
    {
        String result =null;
        String url="http://apis.juhe.cn/cook/query.php";
        Map params=new HashMap();
        params.put("id","200");//标签id
        params.put("key",APPKEy);
        params.put("dtype","");//json格式返回

        try{
            result =net(url,params,"GET");
            JSONObject object=JSON.parseObject(result);
            if(object.getIntValue("error_code")==0)
            {
                System.out.println(object.get("result"));
            }else {
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */

    public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {

            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }

            //调试。。我们在测试代码的主线程中去访问网络，这样就一定会触发StrictMode的线程监测，，要开启一个新的线程
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectNetwork()
                    .penaltyLog()
                    .build());


            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();

            /*/调试
            if(conn!=null)
            {
                //调试
                System.out.println("trynetconn");
            }*/

            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");

            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();


            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));

            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
        maymenue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRequest1();
                Toast.makeText(getApplicationContext(),"菜谱大全",Toast.LENGTH_SHORT).show();
            }
        });

    }
}
